package com.itheima.controller.store;


import com.github.pagehelper.PageInfo;
import com.itheima.controller.BaseServlet;
import com.itheima.domain.store.Company;
import com.itheima.utils.BeanUtil;


import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@WebServlet("/store/company/*")
public class CompanyServlet extends BaseServlet {

    //查找所有
    public void findAll(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        //获取分页参数
        String pageNum = req.getParameter("pageNum");
        String pageSize = req.getParameter("pageSize");

        //调用方法获取所有信息
        List<Company> list = companyServive.findAll(pageNum, pageSize);

        //使用分页插件处理
        PageInfo<Company> pageInfo = new PageInfo<>(list);

        //放入绘会话域
        req.setAttribute("page", pageInfo);

        //重定向到list.jsp页面
        req.getRequestDispatcher("/pages/store/company/list.jsp").forward(req, resp);

    }

    //添加
    public void save(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取页面数据封装到指定对象中
        Company company = BeanUtil.fillBean(req, Company.class, "yyyy-MM-dd");

        //调用新增方法
        companyServive.save(company);

        //调用查找所有方法
        findAll(req,resp);

    }

    //根据id删除
    public void deleteByIds(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取删除参数
        String ids = req.getParameter("ids");

        //调用删除方法
        Boolean flag = companyServive.deleteByIds(ids);

        //如果删除成功调用查找所有，如果失败显示到错误页面
        if(flag){
            findAll(req,resp);
        }else {
            req.getRequestDispatcher("/pages/error.jsp").forward(req,resp);
        }
    }

    //根据id查找
    public void findById(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取查找参数
        String id = req.getParameter("id");

        //调用查找方法
        Company company = companyServive.findById(id);

        //将查找对象存储入会话域
        req.setAttribute("company",company);

        //跳转到更新页面
        req.getRequestDispatcher("/pages/store/company/update.jsp").forward(req,resp);
    }

    //根据id更新
    public void update(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取页面数据封装到指定对象中
        Company company = BeanUtil.fillBean(req, Company.class);
        //调用更新方法
        companyServive.update(company);


        //跳转到查找所有
        findAll(req,resp);
    }
}
